<template>
  <div>
    <!--     搜索条件-->
    <SearchForm @search="getTableData" @reset="clearSearch">
      <el-col :span="8" :xs="24" v-show="$permiss[564]">
        <el-form-item :label="$t('所属租户')" prop="systemUserId">
          <el-select style="width: 100%" v-model="page.systemUserId" clearable>
            <el-option v-for="item in tenantList" :key="item.adminUserId" :label="item.adminName"
                       :value="item.adminUserId"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('公告标题')" prop="title">
          <el-input v-model="page.title"/>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('新建日期')" prop="createTime">
          <el-date-picker
              style="width: 100%"
              v-model="page.createTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              :placeholder="$t('选择日期时间')"
          />
        </el-form-item>
      </el-col>
    </SearchForm>

    <el-card shadow="never" style="margin-top: 10px">
      <div style="text-align: right;margin-bottom: 10px">
        <el-button type="primary" @click="tableRows('add')" v-show="$permiss[217]">{{ $t('新增') }}</el-button>
      </div>
      <Table :page="page" :table-column="tableColumn" :table-data="tableData" @handleSizeChange="handleSizeChange"
             @handleCurrentChange="handleCurrentChange">
        <el-table-column :label="$t('公告标题')" prop="title" align="center" width="150"></el-table-column>
        <el-table-column :label="$t('公告内容')" align="center" prop="content" width="300">
        </el-table-column>
        <el-table-column :label="$t('资源URL')" prop="resourceUrl" align="center" width="200px"></el-table-column>
        <el-table-column :label="$t('所属对象')" prop="appName" align="center" width="100px">
          <template slot-scope="{row}">
            <div v-if="row.productList && row.productList.length">
              <el-tag style="margin: 5px 5px 0 0" v-for="item in row.productList" :disable-transitions="true" :key="item">{{
                  item.productName
                }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column v-if="$permiss[564]" :label="$t('所属租户')" prop="systemUserName" align="center"
                         width="100px"></el-table-column>
        <el-table-column :label="$t('创建人')" prop="createUserName" align="center"></el-table-column>
        <el-table-column :label="$t('起止时间')" align="center" width="300px">
          <template slot-scope="{row}">
            {{ row.startTime + ' ~ ' + row.endTime }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('新建时间')" prop="createTime" align="center" width="150px"></el-table-column>
        <el-table-column :label="$t('备注')" prop="remarks" align="center" width="200px"></el-table-column>
        <el-table-column :label="$t('状态')" align="center">
          <template slot-scope="{row}">
            <el-switch @change="changeStatus(row)" :disabled="!$permiss[565]"
                       :value="row.status === 1"/>
          </template>
        </el-table-column>
        <el-table-column :label="$t('操作')" align="center" width="150" v-if=" $permiss[219]">
          <template slot-scope="{row}">
            <el-button type="text" @click="tableRows('edit',row)" v-show="adminUserAnth(row)">
              {{ $t('编辑') }}
            </el-button>
            <el-button type="text" @click="delList(row)" v-show="$permiss[219]">{{ $t('删除') }}</el-button>
          </template>
        </el-table-column>
      </Table>
    </el-card>
    <Dialog :visible.sync="visible.isShow" :title="visible.title" @cancel="visible.isShow = false"
            :footer="$permiss[562] ? true : false" @close="clearForm" @confirm="visibleConfirm">
      <el-form label-width="80px" :rules="rulesForm" :model="form" ref="form">
        <el-form-item :label="$t('公告标题')" prop="title">
          <el-input v-model="form.title"/>
        </el-form-item>
        <el-form-item :label="$t('公告内容')" prop="content">
          <el-input type="textarea" :rows="4" v-model="form.content"/>
        </el-form-item>
        <el-form-item :label="$t('资源URL')" prop="resourceUrl">
          <el-input v-model="form.resourceUrl"/>
        </el-form-item>
        <el-form-item :label="$t('起止时间')" prop="beginTime">
          <el-date-picker
              style="width: 100%"
              v-model="form.beginTime"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetimerange"
              unlink-panels
              :default-time="['00:00:00', '23:59:59']"
              range-separator="~"
              :start-placeholder="$t('开始日期')"
              :end-placeholder="$t('结束日期')">
          </el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('公告对象')" prop="productList" v-if="$permiss[561]">
          <!--          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">{{$t('全选') }}</el-checkbox>-->
          <el-checkbox-group v-model="form.productList" @change="handleCheckedChange">
            <el-checkbox v-for="item in productList" :label="item.productName" :key="item.productId">{{
                item.appName
              }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item :label="$t('备注')" prop="remarks">
          <el-input :rows="3" type="textarea" v-model="form.remarks"/>
        </el-form-item>
        <el-form-item :label="$t('状态')" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">{{ $t('启用') }}</el-radio>
            <el-radio :label="0">{{ $t('禁用') }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </Dialog>
  </div>
</template>

<script>
import {dateFormatSection, deepClone} from "@/utils/tools";
import {selectTenant, selectProduct} from "@/api/system";
import {
  systemNoticeAdd,
  systemNoticeDelete,
  systemNoticeUpdate,
  systemNoticeList,
  systemNoticeUpdateStatus
} from "@/api/system";

export default {
  name: 'announcement',
  data() {
    return {
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      tenantList: [],
      tableData: [],
      tableColumn: [],
      visible: {
        type: '',
        isShow: false,
        title: ''
      },
      form: {
        status: 1,
        productList: []
      },
      rulesForm: {
        title: [
          {required: true, message: this.$t('不能为空'), trigger: 'change'},
        ],
        content: [
          {required: true, message: this.$t('不能为空'), trigger: 'change'},
        ],
        productList: [
          {type: 'array', required: true, message: this.$t('请选择APP'), trigger: 'change'},
        ],
        beginTime: [
          {required: true, message: this.$t('请选择时间'), trigger: 'change'},
        ]
      },
      productList: [],
      checkAll: false,
      isIndeterminate: false
    }
  },

  watch: {},
  async mounted() {
    if (this.$permiss[216]) {
      this.getTableData()
    }
    this.tenantList = await selectTenant().then(res => res.data)
  },
  methods: {
    async getTableData() {
      const res = await systemNoticeList(this.page)
      if (res.code === 1) {
        const {list,  total} = res.data
        this.tableData = list
        this.page = Object.assign({}, this.page, {
          total: total
        })
      }
    },
    clearSearch() {
      this.page = {
        pageNum: 1,
        pageSize: 10,
        total: 0
      }
      this.getTableData()
    },
    handleCurrentChange(val) {
      this.page.pageNum = val
      this.getTableData()
    },
    handleSizeChange(val) {
      this.page.pageSize = val
      this.getTableData()
    },

    // 复选框全选
    handleCheckAllChange(value) {
      this.form.productList = value ? this.productList.map(item => item.productName) : []
      this.isIndeterminate = false
    },
    // 选中产品
    handleCheckedChange(value) {
      this.checkAll = value.length === this.productList.length
      this.isIndeterminate = value.length > 0 && value < this.productList.length;
    },
    async tableRows(type, row) {
      // 获取产品列表
      const productRes = await selectProduct()
      this.productList = productRes.data
      if (type === 'add') {
        // 新增
        this.addList()
      } else {
        // 编辑
        this.editList(row)
      }
    },
    adminUserAnth() {
      if (!this.page.systemUserId && this.$permiss[564]) {
        return true
      } else if (!this.page.systemUserId && !this.$permiss[564]) {
        return true
      } else {
        return false
      }
    },
    // 新增列表
    addList() {
      this.visible = {
        isShow: true,
        type: 'add',
        title: this.$t('新增')
      }
    },
    // 编辑列表
    editList(row) {
      this.form = Object.assign({}, deepClone(row), {
        productList: row.productList.map(item => item.productName),
        beginTime: [row.startTime, row.endTime]
      })
      // this.checkAll = row.productList.length === this.productList.length
      // this.isIndeterminate = this.form.productList.length > 0 && this.form.productList < this.productList.length;
      this.visible = {
        isShow: true,
        type: 'edit',
        title: this.$t('编辑')
      }
    },
    // 删除公告
    delList(row) {
      this.$confirm(this.$t('确定删除?'), this.$t('提示')).then(async () => {
        const res = await systemNoticeDelete({id: row.id})
        if (res.code === 1) {
          this.$message.success(this.$t('删除成功'))
          this.getTableData()
        }
      }).catch(() => {
      })
    },
    // 切换状态
    async changeStatus(row) {
      const res = await systemNoticeUpdateStatus({
        status: row.status === 0 ? 1 : 0,
        id: row.id
      })
      if (res.code === 1) {
        this.$message.success(this.$t('修改成功'))
        this.getTableData()
      }
    },
    // 表单提交
    async visibleConfirm() {
      this.$refs.form.validate(async v => {
        if (v) {
          let message = ''
          if (this.visible.type === 'add') {
            message = this.$t('新增成功')
          } else {
            message = this.$t('修改成功')
          }
          const productList = []
          this.productList.forEach(item => {
            if (this.form.productList.indexOf(item.productName) !== -1) {
              productList.push(item)
            }
          })
          const [startTime,endTime] = dateFormatSection(this.form.beginTime)
          const params = {
            ...this.form,
            startTime,endTime,
            productList
          }
          delete params.beginTime
          const api = (params) => this.visible.type === 'add' ? systemNoticeAdd(params) : systemNoticeUpdate(params)
          const res = await api(params)
          if (res.code === 1) {
            this.$message.success(message)
            this.visible.isShow = false
            this.getTableData()
          }
        }
      })
    },
    // 清空表单操作记录
    async clearForm() {
      this.form = {
        status: 1,
        productList: []
      }
      this.checkAll = false
      this.isIndeterminate = false
      this.$refs.form.resetFields()
    },
  },
}
</script>

<style scoped>

</style>
